/**
 * 
 */

$(document).ready(function() {
	var allRegions= uft.getProfileUniqueRegions()
	var getDefaultMaxRequest=uft.getDefaultHttpMaxRequest();
	if( !jQuery.isEmptyObject(allRegions)){
		dwr.util.addOptions("regionListSelect",allRegions)
		$("#regionListSelect").focus()
	}
	var allProfileList;
	$( "#regionListSelect" ).change(function() {
	 	if ( $("#regionListSelect").val() != "Region"){
	 		//console.log($("#regionListSelect").val())
	 		allProfileList=uft.getProfileByTypeRegion("HTTPServer",$("#regionListSelect").val())
	 		if( !jQuery.isEmptyObject(allProfileList)){
	 			updateApacheGraphUI()
		 		updateData();
		 		uft.startTimer("AD1",updateData,parseInt($("#apacheSetting-popover-content #refreshInterval").val()));
	 		}else{
	 			$("#index-alert-container").atf_alert_flyover("No Appache HTTP Profiles Found for this Regions", "Oops!")
	 		}
	 		
	 	}
	});
	
	
	$("#refreshUpdateDataBtn").click(function(){
 		updateData();
	})
 	$('#apacheDashboardSettingBtn').popover({ 
	    html : true,
	    placement: 'left',
	    title: function() {
	      return $("#apacheSetting-popover-head").html();
	    },
	    content: function() {
	      return $("#apacheSetting-popover-content").html();
	    }
	});	
	$('#apacheDashboardSettingBtn').on('hidden.bs.popover', function () {
		  // do something…
		if ( jQuery.isNumeric($("#apacheSetting-popover-content #nuOfColumns").val())){
			if ( parseInt($("#apacheSetting-popover-content #nuOfColumns").val()) < 9){
				updateApacheGraphUI()
				updateData();
			}else{
				$("#index-alert-container").atf_alert_flyover("Number of Columns are too High...", "Value Too High")
				$("#apacheSetting-popover-content #nuOfColumns").attr("value", "4")
				updateApacheGraphUI()
				updateData();
				
			}
		}
		
		
		if ( jQuery.isNumeric($("#apacheSetting-popover-content #refreshInterval").val())){
			if ( parseInt($("#apacheSetting-popover-content #refreshInterval").val()) > 1000){
				uft.stopTimer("AD1");
		 		uft.startTimer("AD1",updateData,parseInt($("#apacheSetting-popover-content #refreshInterval").val()));
			}else{
				$("#index-alert-container").atf_alert_flyover("Refresh Interval value is too low...", "Value Too Low")
				$('#apacheSetting-popover-content #refreshInterval').attr('value', "30000")
			}
		}
		
	})
	function updateApacheGraphUI(){
	$('#apacheGraphUIArea').empty();
	if( !jQuery.isEmptyObject(allProfileList)){
	   var numberOfColumns= parseInt($("#apacheSetting-popover-content #nuOfColumns").val());
	   if(numberOfColumns > 12){
	   	numberOfColumns=12;
	   }   		   
	   var profilesSize= allProfileList.length;
	   var rows=Math.ceil(profilesSize/numberOfColumns)
   	  // console.log("profileSize: "+profilesSize)
   	   var noOfItems= 0
	   for (i = 0; i < rows; i++) {
			var row = $('<div>', { 'class':'row'})
			 for (j = 0; j < numberOfColumns; j++) {
			 	var column = $('<div>', { 'class':'col-md-'+Math.floor(12/numberOfColumns), id:'AC'+noOfItems})
			 	noOfItems++;
			 	row.append(column)
			 }
			$('#apacheGraphUIArea').append(row);
		}
		for (k = 0; k < profilesSize; k++) {
			var aPanel=buildApachePanel(allProfileList[k]);
	//		console.log(k)
		//	console.log(aPanel)
			//console.log($("#apacheGraphUIArea div[id='AC"+k+"']"))
			$("#apacheGraphUIArea div[id='AC"+k+"']").append(aPanel);
		}

	}
}

function buildApachePanel(profileObj){
   var maxRequest=uft.getProfilePreference(profileObj,"HTTP_REQUEST_MAX")
   if(maxRequest == ""){maxRequest=getDefaultMaxRequest}
   
	var apacheProfile=$('<div>', {
		'class': 'panel panel-primary',
		 html: [
				$('<div>', {
					'class': 'panel-heading',
					html: [
						$('<i>', { 'class':'fa fa-tachometer fa-fw'}),
						profileObj.profileName
					]
				}),
				$('<div>', {
					'class': 'panel-body',
					id: 'P'+profileObj.id,
					html: [
						$('<div>',{'class':'row', 
							html:[
								$('<div>', {
									'class':'col-md-12,col-lg-12',
									 id: 'P'+profileObj.id+'_requestArea'
								})
							] }),
						$('<div>',{'class':'row',
							html:[
									$('<a>', { 'data-toggle':'collapse','class':'btn btn-small', type:'button'
									,text:'Details', href:'#P'+profileObj.id+'_detailsArea' }),
									$('<a>', { 'data-toggle':'collapse','class':'btn btn-small', type:'button'
									,text:'Applications', href:'#P'+profileObj.id+'_appListArea' }),
									$('<div>',{ id:'P'+profileObj.id+'_detailsArea', 'class':'panel-collapse collapse',
										html: [
											$('<div>', {
												'class':'col-md-12,col-lg-12' ,
												html: [
													$('<div>',{
														'class':'table-responsive',
														html: [
															$('<table>', {
															    'class': 'table table-striped',
																html: [
																	$('<tr>', { html:[$('<td>',{text:'Profile Name:'}), $('<td>', { text:profileObj.profileName})]}),
																	$('<tr>', { html:[$('<td>',{text:'Region:'}), $('<td>', { text:profileObj.region})]}),
																	$('<tr>', { html:[$('<td>',{text:'URL:'}), $('<td>', { html:[$('<a>',{text:'URL',href:'http://'+profileObj.hostname+':'+profileObj.port+'/'+profileObj.url, target:'_blank'})]})]}),
																	$('<tr>', { html:[$('<td>',{text:'Max Requests:'}), $('<td>', {id: 'P'+profileObj.id+"_maxRequest", text:maxRequest})]}),
																	$('<tr>', { html:[$('<td>',{text:'IdleWorkers:'}), $('<td>', { id: 'P'+profileObj.id+"_idleWorkers",})]}),
																	$('<tr>', { html:[$('<td>',{text:'ServerUptime:'}), $('<td>', { id: 'P'+profileObj.id+"_serverUptime",})]}),
																	$('<tr>', { html:[$('<td>',{text:'CurrentTime:'}), $('<td>', { id: 'P'+profileObj.id+"_currentTime",})]})
																]
															})
														]
													})
												]
											})
										]
										}),
									$('<div>',{ id:'P'+profileObj.id+'_appListArea', 'class':'panel-collapse collapse',
										html: [getApplicationListTable(profileObj)]}),
									
								] 
							})
					]
				})
			]
	})
	return apacheProfile;
}

function getApplicationListTable(profileObj){
	 var applicationsList=uft.getProfilePreference(profileObj,"HTTP_APP_LIST")
	 var appList="<p>";
	 if(applicationsList != ""){
	 	var appListArray = applicationsList.split(",");
	 	jQuery.each( appListArray, function( i, val ) {
			appList=appList+" "+val
		})
	 }
	 appList=appList+"</p>";
	 return appList;
}
function updateOrCreateRequestChart(id, url){	
	  apacheDashboardController.getApacheStatusDetails(url,{
		  callback:function(result){
			// data.push([result.currentTime,result.currentRequests])
			$("#P"+id+"_requestArea").empty();
			 var g = new JustGage({
				 id: "P"+id+"_requestArea",
				 value: parseInt(result.currentRequests),
				 min: 0,
				 max: parseInt($("#P"+id+"_maxRequest").text()),
				 relativeGaugeSize: true,
				 title: "Requests"
				
			}); 
			$("#P"+id+"_idleWorkers").text(result.idleWorkers);
			$("#P"+id+"_serverUptime").text(result.serverUptime);
			$("#P"+id+"_currentTime").text(result.currentTime);
		  },
		  errorHandler:function(errorString, exception){
			  
		  }
	  })
	 // console.log(data)
	  
}
var updateData = function updateDataFn(){
	
		if(  $("#dashboardTabs li.active a" ).text() == "Apache HTTP" && $("#apacheGraphUIArea").children().size() >0 ){
			if( !jQuery.isEmptyObject(allProfileList)){
			 dwr.engine.beginBatch()
			 jQuery.each( allProfileList, function( i, val ) {
			 	 updateOrCreateRequestChart(val.id,'http://'+val.hostname+':'+val.port+'/'+val.url)
			 })
			 dwr.engine.endBatch()
			}
		}else{
			uft.stopTimer("AD1");
		}
}

	
	
	
// 	refreshIntervalId = setInterval(function(){
// 	 if( $("#apacheGraphUIArea").visible()){
// 	 	updateData()
// 	 }else{
// 	 	clearTimeout(refreshIntervalId)
// 	 }
		
// 	 }, 10000);

})